package org.openwebtop.sunshine.action.history;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.openwebtop.sunshine.dao.CodeRepositoryDAO;
import org.openwebtop.sunshine.domain.CodeRepository;
import org.openwebtop.sunshine.subversion.SubversionClient;
import org.openwebtop.sunshine.subversion.SubversionClientFactory;
import org.openwebtop.sunshine.subversion.model.RevisionInfo;

import com.opensymphony.xwork.ActionSupport;

public class HistoryListAction {
	private final static int DEFAULT_PAGE_SIZE = 10;

	private SubversionClientFactory subversionClientFactory;
	private CodeRepositoryDAO codeRepositoryDAO;

	// Getter
	private CodeRepository codeRepository;
	private List<RevisionInfo> revisionInfos;

	// Params
	private String name;
	private long to;
	private long from;
	private int size;

	public String execute() throws Exception {
		if (StringUtils.isNotBlank(name)) {
			codeRepository = codeRepositoryDAO.getCodeRepository(name);

			if (codeRepository != null) {
				final SubversionClient subversionClient = subversionClientFactory.getSubversionClient(codeRepository);
				final long lastestRevision = subversionClient.getLastestRevision();

				if (to <= 0 || to > lastestRevision) {
					to = 0;
				}

				if (from <= 0 || from > lastestRevision) {
					from = lastestRevision;
				}

				if (size == 0 || size > 50) {
					size = DEFAULT_PAGE_SIZE;
				}

				if (to > 0) {
					revisionInfos = subversionClient.getRevisionInfoListFromLast(to, size);
				} else {
					revisionInfos = subversionClient.getRevisionInfoListToBase(from, size);
				}
			}
		}

		return ActionSupport.SUCCESS;
	}

	public void setCodeRepositoryDAO(CodeRepositoryDAO codeRepositoryDAO) {
		this.codeRepositoryDAO = codeRepositoryDAO;
	}

	public void setSubversionClientFactory(SubversionClientFactory subversionClientFactory) {
		this.subversionClientFactory = subversionClientFactory;
	}

	public CodeRepository getCodeRepository() {
		return codeRepository;
	}

	public List<RevisionInfo> getRevisionInfos() {
		return revisionInfos;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setTo(long to) {
		this.to = to;
	}

	public void setFrom(long from) {
		this.from = from;
	}

	public void setSize(int size) {
		this.size = size;
	}

}
